#include <BackgroundSubtractor/rgbthresh.h>
#include <highgui.h>

BackgroundSubtractorRGBThresh::BackgroundSubtractorRGBThresh(const cv::Mat& _bgimage, const cv::Scalar& _thresh)
:bgimage(_bgimage.clone()), thresh(_thresh){
	ch.resize(3);
}

BackgroundSubtractorRGBThresh::BackgroundSubtractorRGBThresh(const cv::Scalar& _thresh)
:thresh(_thresh){
	ch.resize(3);
}

BackgroundSubtractorRGBThresh::~BackgroundSubtractorRGBThresh(){
}

BackgroundSubtractorRGBThresh::BackgroundSubtractorRGBThresh(const BackgroundSubtractorRGBThresh& other){
	*this=other;
}

const BackgroundSubtractorRGBThresh& BackgroundSubtractorRGBThresh::operator=(const BackgroundSubtractorRGBThresh& other){
	this->bgimage=other.bgimage.clone();
	this->thresh=other.thresh;
	this->isInit=other.isInit;
	this->diff=other.diff.clone();
	ch.clear();
	for(std::vector<cv::Mat>::const_iterator it=other.ch.begin(); it!=other.ch.end(); it++){
		this->ch.push_back(it->clone());
	}
	return *this;
}

void BackgroundSubtractorRGBThresh::setBGImage(const cv::Mat& _bgimage){
	this->bgimage=_bgimage.clone();
}

void BackgroundSubtractorRGBThresh::setBGImage(const std::string& bgfilename){
	bgimage=cv::imread(bgfilename);
}

cv::Mat BackgroundSubtractorRGBThresh::getBGImage()const{
	return bgimage;
}

cv::Scalar BackgroundSubtractorRGBThresh::getThreshold()const{
	return thresh;
}

void BackgroundSubtractorRGBThresh::setThreshold(const cv::Scalar& _thresh){
	this->thresh=_thresh;
}

void BackgroundSubtractorRGBThresh::apply(const cv::Mat& img, cv::Mat& oimg){
	if( bgimage.empty() ) throw "No background image";
	if( img.type() != bgimage.type() ) throw "Different Type";


	cv::absdiff(img, bgimage, diff);
	cv::split(diff, ch);

	int i=0;
	oimg=cv::Mat::ones(img.size(),CV_8UC1)*255;
	cv::Mat temp;
	for(std::vector<cv::Mat>::iterator it=ch.begin(); it!=ch.end(); it++, i++){
		cv::threshold(*it, temp, thresh[i],255,CV_THRESH_BINARY);
		oimg= oimg & temp;
	}
}
